package priv.mill.simple;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class PackageEncoder extends MessageToByteEncoder<PackageObj>{

	@Override
	protected void encode(ChannelHandlerContext ctx, PackageObj p, ByteBuf b) throws Exception {
		byte[] byteArray = toBytes(p);
		b.writeInt(byteArray.length);
		b.writeBytes(byteArray);
	}

	public byte[] toBytes(PackageObj p) throws IOException {
		byte[] byteArray = null;
		try(ByteArrayOutputStream bOut = new ByteArrayOutputStream();
				ObjectOutputStream oOut = new ObjectOutputStream(bOut);) {
			oOut.writeObject(p);
			byteArray = bOut.toByteArray();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return byteArray;
	}

}
